import pygame
import random
from datetime import datetime, timedelta

class Player:
    def __init__(self, name, ability):
        self.name = name
        self.ability = ability  # 1-9
        self.stamina = 10  # 最大10
        self.original_stamina = 10  # 记录初始体力，用于显示体力条
        self.match_stamina = 10 # 新增：比赛专用体力
        self.bio = ""  # 球员简介
        
    def __str__(self):
        return f"{self.name} (能力: {self.ability}, 体力: {self.stamina})"
    
    def recover_stamina(self, amount, cost_per_point=0, team_balance=None):
        """恢复体力，可能需要消耗虚拟币"""
        if cost_per_point == 0 or team_balance is None:
            # 无需消耗虚拟币
            self.stamina = min(10, self.stamina - self.match_stamina + amount)
            return 0
            
        # 需要消耗虚拟币
        max_possible = min(10 - self.stamina + self.match_stamina, team_balance // cost_per_point)
        if max_possible > 0:
            self.stamina += max_possible
            cost = max_possible * cost_per_point
            return cost
        return 0

class Team:
    def __init__(self, name, prototype):
        self.name = name
        self.prototype = prototype  # 原型球队
        self.players = []
        self.points = 0
        self.goals_scored = 0 #进球数
        self.goals_conceded = 0 #失球数 
        self.head_goals = 0  # 头球数
        self.matches_played = 0
        self.home_wins = 0
        self.home_losses = 0
        self.is_national_team = False  # 是否为国家二队
        self.is_in_world_cup = False  # 是否参加世界杯预选赛
        self.last_year_points = 0  # 上一年积分，用于中超计算
        self.golden_age = False  # 是否处于金元足球时期
        self.balance = 0  # 虚拟币余额
        self.wins = 0
        self.draws = 0
        self.losses = 0
        self.season_goals = 0  # 本赛季进球数
        self.season_conceded = 0  # 本赛季失球数
        self.stage_goals = 0  # 阶段总进球数
        self.relegation_risk = 0  # 保级风险 0-100
        self.championship_chance = 0  # 夺冠概率 0-100
        
    def add_player(self, player):
        self.players.append(player)
        
    def get_available_players(self):
        return [p for p in self.players if p.match_stamina > 0]
        
    def calculate_goal_difference(self):
        return self.goals_scored - self.goals_conceded
        
    def __str__(self):
        return f"{self.name} - 积分: {self.points}, 进球: {self.goals_scored}, 失球: {self.goals_conceded}, 净胜球: {self.calculate_goal_difference()}"
    
    def recover_players_stamina(self, amount, stage):
        """恢复所有球员的体力"""
        total_cost = 0
        cost_per_point = 0
        
        # 根据阶段确定恢复成本
        if stage == 2:
            cost_per_point = 100
        elif stage == 3:
            cost_per_point = 500
            
        for player in self.players:
            cost = player.recover_stamina(amount, cost_per_point, self.balance)
            total_cost += cost
            self.balance -= cost
            
        return total_cost

class Match:
    def __init__(self, match_number,match_count, home_team, away_team, stage, year, is_user_involved=False):
        self.match_number = match_number
        self.home_team = home_team
        self.away_team = away_team
        self.home_goals = 0  # 初始为None，表示未确定
        self.away_goals = 0
        self.stage = stage
        self.year = year
        self.home_head_goals = 0
        self.away_head_goals = 0
        self.events = []  # 比赛事件记录
        self.minute = 0  # 当前比赛分钟
        self.home_streak = 0  # 主场连续优势次数
        self.away_streak = 0  # 客场连续优势次数
        self.home_player_index = 0
        self.away_player_index = 0
        self.match_count = match_count # 新增场次match_count属性
        self.completed = False  # 比赛是否完成
        self.is_user_involved = is_user_involved  # 是否涉及用户球队
        self.opponent_match_stamina = 0 # 添加对方比赛体力属性
            
    def play_step(self, user_team, bribe_used=False, must_lose=False):
        """执行比赛的一步（一分钟）"""
        if self.completed:
            return True
            
        self.minute += 1
        if self.minute > 50:
            self.completed = True
            return True
            
        # 检查是否有可用球员
        home_available = self.home_team.get_available_players()
        away_available = self.away_team.get_available_players()
        
        if not home_available and not away_available:
            # 一方没有可用球员，比赛提前结束
            self.completed = True
            return True
        if home_available :
            home_player = home_available[self.home_player_index % len(home_available)]
            home_ability = home_player.ability
            if home_player.stamina <= 3:
               home_ability = max(1, home_ability - 2)
            home_roll = random.randint(1, home_ability)
            home_player.match_stamina = max(0, home_player.match_stamina - 1)
            home_player.stamina = max(0, home_player.stamina - 1)
            self.home_player_index += 1
        else:
            home_roll = 2
        if away_available :    
            # 轮换球员
        
            away_player = away_available[self.away_player_index % len(away_available)]
        
            # 应用能力值调整（体力不足时）
        
            away_ability = away_player.ability
        
        
            if away_player.stamina <= 3:
                away_ability = max(1, away_ability - 2)
        
            # 掷骰子
        
            away_roll = random.randint(1, away_ability)
            #消耗体力
            away_player.match_stamina = max(0, away_player.match_stamina - 1)
            away_player.stamina = max(0, away_player.stamina - 1)
        
            self.away_player_index += 1
        else:
            away_roll = 2

        # 检查赌球事件（第二阶段及以后）
        if self.stage >= 2 and not self.home_team.golden_age and not self.away_team.golden_age:
            if home_roll == away_roll:
                event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: 赌球！{self.home_team.name}朝自己球门踢了一个乌龙球！"
                self.events.append(event_text)
                self.away_goals += 1 if self.away_goals is not None else 1
                
                return False
        
        
        
        # 判断谁赢了这一轮
        is_head_goal = False
        event_text = None
        if home_roll > away_roll:
            self.home_streak += 1
            self.away_streak = 0
            # 检查是否是头球（第一阶段第四年起）
            if (self.stage == 1 and self.year >= 4) or self.stage >= 2:
                is_head_goal = (home_roll == home_ability)
            
            # 根据连续优势次数输出不同事件
            if self.home_streak == 1:
                event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.home_team.name}获得球权！"
            elif self.home_streak == 2:
                event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.home_team.name}传球！"
            elif self.home_streak >= 3:
                # 保持原有的进球逻辑
                pass
        elif away_roll > home_roll:
            self.away_streak += 1
            self.home_streak = 0
            # 检查是否是头球
            if (self.stage == 1 and self.year >= 4) or self.stage >= 2:
                is_head_goal = (away_roll == away_ability)
            
            # 根据连续优势次数输出不同事件
            if self.away_streak == 1:
                event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.away_team.name}获得球权！"
            elif self.away_streak == 2:
                event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.away_team.name}传球！"
            elif self.away_streak >= 3:
                # 保持原有的进球逻辑
                pass
        else:
            #self.home_streak = 0
            #self.away_streak = 0
            event_text = f"{home_roll}:{away_roll}第{self.minute}分钟: 双方争夺激烈，暂无优势！"
        
        # 添加事件文本（如果有）
        if event_text:
            self.events.append(event_text)


        
        # 检查是否进球（连续3次优势）
        goal_scored = False
        if self.home_streak >= 3:
            goal_value = 2 if (self.stage == 1 and self.year >= 4 and is_head_goal) else 1
            self.home_goals += goal_value
            if is_head_goal:
                self.home_head_goals += 1
            goal_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.home_team.name}进球了，当前比分{self.home_goals}:{self.away_goals}"
            if is_head_goal:
                goal_text += " (头球)"
                if goal_value > 1:
                    goal_text += f"，算{goal_value}球"
            self.events.append(goal_text)
            self.home_streak = 0
            self.away_streak = 0
            goal_scored = True
        
        if self.away_streak >= 3:
            goal_value = 2 if (self.stage == 1 and self.year >= 4 and is_head_goal) else 1
            self.away_goals += goal_value
            if is_head_goal:
                self.away_head_goals += 1
            goal_text = f"{home_roll}:{away_roll}第{self.minute}分钟: {self.away_team.name}进球了，当前比分{self.home_goals}:{self.away_goals}"
            if is_head_goal:
                goal_text += " (头球)"
                if goal_value > 1:
                    goal_text += f"，算{goal_value}球"
            self.events.append(goal_text)
            self.home_streak = 0
            self.away_streak = 0
            goal_scored = True
        
        # 每10分钟记录一次比赛状态
        # if self.minute % 3 == 0 and not goal_scored:
        #     self.events.append(f"第{self.minute}分钟: 比分 {self.home_goals}:{self.away_goals}")
        self.home_player_index += 1
        self.away_player_index += 1
        
        return False
    
    def finalize(self, user_team, game):
        """比赛结束，更新统计数据"""

        #将比赛结果写入赛事表
        game.modify_match_score(self.match_count,self.match_number, self.home_goals, self.away_goals)
        #比赛场次加1
        self.match_count += 1
        # 更新比赛次数
        self.home_team.matches_played += 1
        self.away_team.matches_played += 1
        
        # 更新进球和失球
        self.home_team.goals_scored += self.home_goals
        self.home_team.goals_conceded += self.away_goals
        self.away_team.goals_scored += self.away_goals
        self.away_team.goals_conceded += self.home_goals
        
        # 更新头球数
        self.home_team.head_goals += self.home_head_goals
        self.away_team.head_goals += self.away_head_goals
        
        # 更新积分
        result_text = ""
        if self.home_goals > self.away_goals:
            self.home_team.points += 3
            self.home_team.home_wins += 1
            result_text = f"{self.home_team.name} 获胜"
        elif self.away_goals > self.home_goals:
            self.away_team.points += 3
            self.home_team.home_losses += 1
            result_text = f"{self.away_team.name} 获胜"
        else:
            self.home_team.points += 1
            self.away_team.points += 1
            result_text = "平局"
        
        self.events.append(f"\n比赛结束: {self.home_team.name} {self.home_goals} : {self.away_goals} {self.away_team.name}")
        self.events.append(result_text)
        
        # 发放奖金
        reward = 0
        if self.home_team == user_team:
            if self.home_goals > self.away_goals:
                reward = 4000 if self.stage >= 2 else 3000
                self.home_team.balance += reward
                self.events.append(f"获得比赛胜利奖金{reward}元")
        elif self.away_team == user_team:
            if self.away_goals > self.home_goals:
                reward = 4000 if self.stage >= 2 else 3000
                self.away_team.balance += reward
                self.events.append(f"获得比赛胜利奖金{reward}元")
                
        return result_text

class Message:
    def __init__(self, source, content, date, is_task=False, completed=False):
        self.source = source
        self.content = content
        self.date = date
        self.is_task = is_task
        self.completed = completed
        self.read = False
        
    def __str__(self):
        status = "【已完成】" if self.completed else "【未完成】" if self.is_task else ""
        return f"{self.date.strftime('%Y-%m-%d')} {self.source}: {self.content} {status}"